package com.onegene.pdf.component.event;

import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;

/**
 * @author laoliangliang
 * @since 2020-05-24 13:53
 */
public class PageNumberEvent implements IEventHandler {

    private Document doc;
    private int offset;
    private Style style;

    public PageNumberEvent(Document doc, int offset) {
        this.doc = doc;
        this.offset = offset;
    }

    public PageNumberEvent(Document doc, int offset, Style style) {
        this.doc = doc;
        this.offset = offset;
        this.style = style;
    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PageSize pageSize = pdfDoc.getDefaultPageSize();
        int pageNumber = pdfDoc.getNumberOfPages();
        doc.showTextAligned(new Paragraph(String.format("%02d", pageNumber + offset)).addStyle(style), pageSize.getWidth() / 2, 42, pageNumber, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0);
    }
}
